const { exec } = require("./index");

exports.getOrderById = async function ({ id }) {
  const sql = `select * from orderList where id = ?`;
  const result = await exec(sql, [id]);
  return result;
};
exports.addOrderList = async function ({
  createTime,
  goods,
  totalPrice,
  address,
  state,
  uid,
}) {
  const sql = `INSERT INTO orderList (id, createTime, goods, totalPrice, address, state, uid) VALUES (NULL, ?, ?, ?, ?, ?, ?)`;
  const result = await exec(sql, [
    createTime,
    goods,
    totalPrice,
    address,
    state,
    uid,
  ]);
  return result;
};

exports.order = async function ({ uid, state }) {
  const sql = `select * from orderList where uid = ?`;
  const sql1 = `select * from orderList where uid = ? and state = ?`;
  if (state) {
    return await exec(sql1, [uid, state]);
  } else {
    return await exec(sql, [uid]);
  }
};

exports.getOrderCount = async function ({ uid }) {
  const sql = `SELECT 
    SUM(CASE WHEN state = 1 and uid = ? THEN 1 ELSE 0 END) AS count_state_1,
    SUM(CASE WHEN state = 2 and uid = ? THEN 1 ELSE 0 END) AS count_state_2,
    SUM(CASE WHEN state = 3 and uid = ? THEN 1 ELSE 0 END) AS count_state_3,
    SUM(CASE WHEN state = 4 and uid = ? THEN 1 ELSE 0 END) AS count_state_4
FROM
    orderList;`;
  return await exec(sql, [uid, uid, uid, uid])
};

exports.deleteOrder = async function ({ uid, id }) {
  const sql = `DELETE FROM orderList WHERE id = ? and uid = ?;`
  return await exec(sql, [id, uid])
}


exports.editOrder = async function ({ id, state }) {
  const sql = `UPDATE orderList SET state = ? WHERE id = ?;`
  return await exec(sql, [state, id])
}
